package org.onion.pattern.kit.common.jackson.serializer.duration;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.convert.DurationStyle;

import java.io.IOException;
import java.time.Duration;

public class DayDurationDeserializer extends JsonDeserializer<Duration> {

    public static final DayDurationDeserializer INSTANCE = new DayDurationDeserializer();

    @Override
    public Duration deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        if (ObjectUtils.isEmpty(jsonParser)) {
            return null;
        }

        try {
            long longValue = jsonParser.getLongValue();
            return Duration.ofDays(longValue);
        } catch (Exception e) {
            //
        }

        String txt = jsonParser.getText();

        if (StringUtils.isNumeric(txt)) {
            return Duration.ofDays(Long.parseLong(txt));
        }

        try {
            return com.fasterxml.jackson.datatype.jsr310.deser.DurationDeserializer.INSTANCE.deserialize(jsonParser, ctxt);
        } catch (Exception e) {
            //...
        }

        DurationStyle detect = DurationStyle.detect(txt);
        return detect.parse(txt);
    }


}
